package home

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"ttsx/server/common/global"
	"ttsx/server/model"
)

func ToIndex(ctx *gin.Context) {
	// 获取cookies信息
	var NewUser model.User
	cookies, _ := ctx.Cookie("username")
	if cookies == "" {
		NewUser.Name = ""
	}
	if ret := global.App.DB.Where("name = ?", cookies).Find(&NewUser); ret.RowsAffected == 0 {
		NewUser.Name = ""
	}
	if !NewUser.IsActive {
		NewUser.Name = ""
	}

	// 查询redis中的购物车数量
	cartKey := fmt.Sprintf("cartKey_%d", NewUser.ID)
	cartNum, _ := global.App.RDB.HLen(ctx, cartKey).Result()

	// 商品分类
	var NewGoodsType_list []model.GoodsType
	global.App.DB.Find(&NewGoodsType_list)
	global.App.Log.Sugar().Infof("商品分类信息: %v", NewGoodsType_list)

	// 商品轮询图
	var NewGoodsLoop_list []model.IndexGoodsLoop
	global.App.DB.Find(&NewGoodsLoop_list).Order("index desc")
	global.App.Log.Sugar().Infof("商品轮询图信息: %v", NewGoodsLoop_list)

	// 促销商品图
	var NewGoodsPromo_list []model.IndexGoodsPromo
	global.App.DB.Find(&NewGoodsPromo_list).Order("index desc")
	global.App.Log.Sugar().Infof("促销商品信息: %v", NewGoodsPromo_list)

	// 首页商品数据
	goods := make(map[int]interface{}, len(NewGoodsType_list))
	for _, v := range NewGoodsType_list {

		// 获取文字类型的商品
		var textGoods []map[string]interface{}
		global.App.DB.Model(&model.IndexGoodsType{}).
			Select("tb_index_goods_type.goods_sku_id", "tb_goods_sku.name").
			Joins("left join tb_goods_type on tb_goods_type.id=tb_index_goods_type.goods_type_id").
			Joins("left join tb_goods_sku on tb_goods_sku.id=tb_index_goods_type.goods_sku_id").
			Where("display_type = ?", 0).
			Where("tb_index_goods_type.goods_type_id = ?", v.ID).
			Order("tb_goods_type.name, tb_index_goods_type.index desc").
			Scan(&textGoods)
		global.App.Log.Sugar().Infof("文字类型的商品信息: %v", textGoods)

		// 获取图片类型的商品
		var imageGoods []map[string]interface{}
		global.App.DB.Model(&model.IndexGoodsType{}).
			Select("tb_index_goods_type.goods_sku_id", "tb_goods_sku.name", "tb_goods_sku.image", "tb_goods_sku.price").
			Joins("left join tb_goods_type on tb_goods_type.id=tb_index_goods_type.goods_type_id").
			Joins("left join tb_goods_sku on tb_goods_sku.id=tb_index_goods_type.goods_sku_id").
			Where("display_type = ?", 1).
			Where("tb_index_goods_type.goods_type_id = ?", v.ID).
			Order("tb_goods_type.name, tb_index_goods_type.index").
			Limit(4).
			Scan(&imageGoods)
		global.App.Log.Sugar().Infof("图片类型的商品信息: %v", imageGoods)

		goods[v.ID] = map[string]interface{}{"typeName": v.Name, "typeImage": v.Image, "textGoods": textGoods, "imageGoods": imageGoods}
	}
	global.App.Log.Sugar().Infof("goods: %v", goods)

	ctx.HTML(http.StatusOK, "home/index.html", map[string]interface{}{
		"Name":           NewUser.Name,
		"IsActive":       NewUser.IsActive,
		"GoodsTypeList":  NewGoodsType_list,
		"GoodsLoopList":  NewGoodsLoop_list,
		"GoodsPromoList": NewGoodsPromo_list,
		"Goods":          goods,
		"cartNum":        cartNum,
	})
}
